//
//  AliyunManager.m
//  NetworkDemo
//
//  Created by InitialC on 2017/5/22.
//  Copyright © 2017年 InitialC. All rights reserved.
//

#import "AliyunManager.h"
#import <AliyunOSSiOS/OSSService.h>

NSString * const AccessKey = @"LTAIRMFJYHCNQy9a";
NSString * const SecretKey = @"LybF15ZqmPSo7P2hwmJnDC68bTGOZH";
NSString * const endPoint = @"https://oss-cn-hangzhou.aliyuncs.com";
NSString * const multipartUploadKey = @"multipartUploadObject";
NSString * const ossBucketName = @"testmuta";
#ifdef DEBUG
#define NetCLog(...) NSLog(__VA_ARGS__)
#else
#define NetCLog(...)
#endif

OSSClient * client;
static dispatch_queue_t queue4demo;

@implementation AliyunManager

+ (instancetype)sharedInstance {
    static AliyunManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [AliyunManager new];
    });
    return instance;
}

- (void)setupEnvironment {
#ifdef DEBUG
    [OSSLog enableLog];
#endif
    // 初始化sdk
    [self initOSSClient];
}

- (void)initOSSClient {
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey
                                                                                                            secretKey:SecretKey];
//    NSString *token = @"需要获取和更新oss token";
//    id<OSSCredentialProvider> credentialSecret = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:AccessKey secretKeyId:SecretKey securityToken:token];
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    conf.maxRetryCount = 3;
    conf.timeoutIntervalForRequest = 15;
    conf.timeoutIntervalForResource = 3 * 60 * 60;
    
    client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential clientConfiguration:conf];
}
// 上传完成=>签名
- (void)signAccessObjectURLOfName:(NSString *)fileName handler:(void(^)(BOOL isSuccess, NSString *signURL))completion {
    NSString *publicURL = nil;
    // sign public url
    OSSTask *task = [client presignPublicURLWithBucketName:ossBucketName
                                             withObjectKey:fileName];
    if (!task.error) {
        publicURL = task.result;
        completion(YES, publicURL);
    } else {
        NetCLog(@"地址签名失败 == %@", task.error);
        completion(NO, nil);
    }
}

- (void)uploadObjectAsync:(id)file toFolder:(NSString *)folder withCount:(NSInteger)count withProgress:(ProgressBlock)progressBlock handler:(CompletionBlock)completion {
    [self uploadObjectAsync:file toFolder:folder withName:nil withCount:count withProgress:progressBlock handler:completion];
}

- (void)uploadObjectAsync:(id)file toFolder:(NSString *)folder withName:(NSString *)fileName withCount:(NSInteger)count withProgress:(ProgressBlock)progressBlock handler:(CompletionBlock)completion {
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    // required fields
    UIImage *image;
    if (_type != AliUpdateTypeAudio) {
        if ([file isKindOfClass:[NSData class]]) {
            put.uploadingData = file;
            if ([file length] < 20971520) {
                image = [UIImage imageWithData:file];
            }
        } else if ([file isKindOfClass:[NSURL class]]){
            put.uploadingFileURL = file;
            image = [UIImage imageWithContentsOfFile:[file path]];
        } else {
            completion(NO, nil, nil);
            return;
        }
    } else {
        put.uploadingData = file;
    }
    NSString *oldObjectKeyStr = [AliyunGeneralObject getCurrentTimeStamp:folder]; //[NSString stringWithFormat:@"%@/MUTA_v2_0_3_1_release.apk", folder];
    if (fileName != nil && folder != nil) {
        oldObjectKeyStr = [NSString stringWithFormat:@"%@/iOS/%@", folder, fileName];
    }
    NSString *objectKeyStr = [oldObjectKeyStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    put.bucketName = ossBucketName;
    put.objectKey = objectKeyStr;
    // optional fields
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        //        NetCLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
        Float64 currentBytes = totalByteSent;
        Float64 totalBytes = totalBytesExpectedToSend;
        float progress = currentBytes / totalBytes;
        if (progressBlock != nil) {
            progressBlock(progress);
        }
    };
    //    put.contentType = @"";
    //    put.contentMd5 = @"";
    //    put.contentEncoding = @"";
    //    put.contentDisposition = @"";
    OSSTask *putTask = [client putObject:put];
    __weak __typeof(self)weakSelf = self;
    [putTask continueWithBlock:^id(OSSTask *task) {
//        NetCLog(@"objectKey: %@", put.objectKey);
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (!task.error) {
            [strongSelf signAccessObjectURLOfName:put.objectKey handler:^(BOOL isSuccess, NSString *signURL) {
                if (count == 1 && (weakSelf.type == AliUpdateTypeTailSize || [folder containsString:@"Pengyouquan"])) {
                    signURL = [signURL stringByAppendingString:NSStringFromCGSize(image.size)];
                }
                completion(isSuccess, signURL, put.objectKey);
            }];
        } else {
            NetCLog(@"OSS上传错误 == %@" , task.error, nil);
            completion(NO, nil, nil);
        }
        return nil;
    }];

}

- (void)uploadObjectSync:(id)file toFolder:(NSString *)folder withCount:(NSInteger)count withProgress:(ProgressBlock)progressBlock handler:(CompletionBlock)completion {
    [self uploadObjectSync:file toFolder:folder withName:nil withCount:count withProgress:progressBlock handler:completion];
}

- (void)uploadObjectSync:(id)file toFolder:(NSString *)folder withName:(NSString *)fileName withCount:(NSInteger)count withProgress:(ProgressBlock)progressBlock handler:(CompletionBlock)completion {
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    // required fields
    UIImage *image;
    if (_type != AliUpdateTypeAudio) {
        if ([file isKindOfClass:[NSData class]]) {
            put.uploadingData = file;
            if ([file length] < 20971520) {
                image = [UIImage imageWithData:file];
            }
        } else if ([file isKindOfClass:[NSURL class]]){
            put.uploadingFileURL = file;
            image = [UIImage imageWithContentsOfFile:[file path]];
        } else {
            completion(NO, nil, nil);
            return;
        }
    } else {
        put.uploadingData = file;
    }
    NSString *objectKeyStr = [AliyunGeneralObject getCurrentTimeStamp:folder];
    if (fileName != nil && folder != nil) {
        objectKeyStr = [NSString stringWithFormat:@"%@/iOS/%@", folder, fileName];
    }
    put.bucketName = ossBucketName;
    put.objectKey = objectKeyStr;
    // optional fields
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        //        NetCLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
        Float64 currentBytes = totalByteSent;
        Float64 totalBytes = totalBytesExpectedToSend;
        float progress = currentBytes / totalBytes;
        if (progressBlock != nil) {
            progressBlock(progress);
        }
    };
    //    put.contentType = @"";
    //    put.contentMd5 = @"";
    //    put.contentEncoding = @"";
    //    put.contentDisposition = @"";
    OSSTask *putTask = [client putObject:put];
    [putTask waitUntilFinished];
    if (!putTask.error) {
        [self signAccessObjectURLOfName:put.objectKey handler:^(BOOL isSuccess, NSString *signURL) {
            if (count == 1 && (self.type == AliUpdateTypeTailSize || [folder containsString:@"Pengyouquan"])) {
                signURL = [signURL stringByAppendingString:NSStringFromCGSize(image.size)];
            }
            completion(isSuccess, signURL, put.objectKey);
        }];
    } else {
        NetCLog(@"OSS上传错误 == %@" , putTask.error, nil);
        completion(NO, nil, nil);
    }
    /*
    
    [putTask waitUntilFinished]; // 阻塞直到上传完成
    
    if (!putTask.error) {
        NetCLog(@"upload object success!");
    } else {
        NetCLog(@"upload object failed, error: %@" , putTask.error);
    }
    */
}

@end

@implementation AliyunGeneralObject

+ (NSString *)getCurrentTimeStamp:(NSString *)folder {
    NSTimeInterval recordTime = [[NSDate date] timeIntervalSince1970] * 1000;
    NSString *tempStr = [NSString stringWithFormat:@"%@/iOS/img_%.0f.jpg", folder, recordTime];
    if (folder == nil || [folder containsString:@"Pengyouquan"]) {
        tempStr = [NSString stringWithFormat:@"iOSUpdateFolder/Pengyouquan/img_%.0f.jpg", recordTime];
    }
    return tempStr;
}
+ (NSURL *)getFileLocalUrl:(NSString *)fileName {
    NSURL *url = [[[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil] URLByAppendingPathComponent:fileName];
    return url;
}
+ (UIImage *)resizeImage:(UIImage *)oriImage {
    CGSize newSize = oriImage.size;
    if (newSize.width > 0 && newSize.width < 750) {
        return oriImage;
    } else {
        newSize = CGSizeMake(750, (int)(newSize.height * 750 / newSize.width));
    }
    UIGraphicsBeginImageContext(newSize);
    [oriImage drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}



@end
